package com.polaris.live.popup

import android.content.Context
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.StringUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.hjq.language.LocaleContract
import com.hjq.language.MultiLanguages
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.SetLanguageAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupSetLanguageBinding
import com.polaris.live.manager.AssetsConfigManager
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.InfoModifyBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 应用内语言选择
 * @author Created by 长空 on 2023/12/16/027 17:45
 */
class SetSystemLanguagePopup(
    context: Context,
    private val mViewModel: BaseViewModel,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupSetLanguageBinding
    private val mAdapter by lazy { SetLanguageAdapter() }

    private var mSelectIndex = -1
    private var mLanguage = ""

    override fun getImplLayoutId(): Int {
        return R.layout.popup_set_language
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupSetLanguageBinding.bind(popupImplView)

        if (UserManager.getUser().profile?.appLanguage.isNullOrEmpty()) {
            mBinding.systemLanguage.text =
                StringUtils.getString(string.not_set)
        } else {
            mBinding.systemLanguage.text =
                UserManager.getUser().profile?.appLanguage?.let { CommonUtils.getLanguage(it) }
        }

        val flexBoxLayout = FlexboxLayoutManager(context)
        flexBoxLayout.flexDirection = FlexDirection.ROW
        flexBoxLayout.justifyContent = JustifyContent.FLEX_START
        flexBoxLayout.flexWrap = FlexWrap.WRAP

        mBinding.recycler.apply {
            adapter = mAdapter
            layoutManager = flexBoxLayout
        }

        initListener()
        mViewModel.viewModelScope.launch(CoroutineScopeManager.ioDispatcher) {
            val data = AssetsConfigManager.systemLanguage()
            withContext(CoroutineScopeManager.mainDispatcher) {
                mAdapter.setList(data)
            }
        }
    }

    private fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            mAdapter.clearSelected()

            mAdapter.setSelect(position)
            mSelectIndex = position
        }

        mBinding.saveLanguage.setOnSingleClickListener {
            if (mSelectIndex == -1) {
                ToastGravity.showGravity(context.getString(string.unselected_language))
                return@setOnSingleClickListener
            }
            mLanguage = mAdapter.data[mSelectIndex].language
            mViewModel.requestLoading(
                { userService.infoModify(InfoModifyBean(appLanguage = mLanguage)) },
                {
                    mViewModel.request({ userService.getUserData() }, {
                        UserManager.setUser(it)
                        dismiss()

                        val restart = when (mLanguage) {
                            "zh-CN" -> {//中文简体
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getSimplifiedChineseLocale()
                                )
                            }

                            "zh-TW" -> {//中文繁体
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getTraditionalChineseLocale()
                                )
                            }

                            "en" -> {//英文
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getEnglishLocale()
                                )
                            }

                            "ar" -> {//阿拉伯语
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getArabicLocale()
                                )
                            }

                            "pt" -> {//葡萄牙语
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getPortugalLocale()
                                )
                            }

                            "ja" -> {//日本语
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getJapaneseLocale()
                                )
                            }

                            "ko" -> {//韩语
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getKoreanLocale()
                                )
                            }

                            "es" -> {//西班牙语
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getSpainLocale()
                                )
                            }

                            "ms" -> {//马来语
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getMalayLocale()
                                )
                            }

                            "tr" -> {//土耳其语
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getTurkishLocale()
                                )
                            }

                            "hi" -> {
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getHindiLocale()
                                )
                            }

                            "vi" -> {
                                MultiLanguages.setAppLanguage(
                                    context,
                                    LocaleContract.getVietnameseLocale()
                                )
                            }

                            else -> {
                                false
                            }
                        }
                        if (restart) {
                            AppUtils.relaunchApp()
                        }
                    })
                },
                {
                    ToastGravity.showGravity(it.errorMsg)
                })
        }
    }
}